package models

import (
	"errors"
	"github.com/beego/beego/v2/core/logs"
	"strconv"
	"strings"
	"time"
)

// AdminApi api模型
type AdminApi struct {
	Id          uint      `gorm:"primary_key" json:"id"`
	Path        string    `json:"path"`
	GroupName   string    `json:"group_name"`
	Description string    `json:"description"`
	Method      string    `json:"method"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

// @title 获取api选项数据
func (a *AdminApi) GetOptions() interface{} {
	list := []AdminApi{}

	queryRes := Db.Model(a).Find(&list)

	if queryRes.Error != nil {
		logs.Error(queryRes.Error)
	}

	data := make(map[string][]AdminApi)

	for _, item := range list {
		data[item.GroupName] = append(data[item.GroupName], item)
	}

	res := []TreeOptions{}

	for key, _ := range data {
		temp := []TreeOptions{}
		for _, item := range data[key] {
			temp = append(temp, TreeOptions{
				Label: item.Description,
				Key:   strconv.Itoa(int(item.Id)),
			})
		}

		res = append(res, TreeOptions{
			Label:    key,
			Key:      key,
			Children: temp,
		})
	}

	return res
}

// @title 获取列表
func (a *AdminApi) GetList(page, pageSize int) (interface{}, int64) {
	var total int64
	var list []map[string]interface{}

	res := Db.Model(AdminApi{}).Select("id", "path", "group_name", "description", "method").
		Order("updated_at desc").Limit(pageSize).Offset((page - 1) * pageSize).Find(&list)
	if res.Error != nil {
		logs.Error(res.Error.Error())
	}

	countRes := Db.Model(AdminApi{}).Count(&total)
	if countRes.Error != nil {
		logs.Error(countRes.Error.Error())
	}

	return list, total
}

// @title 获取分组信息
func (a *AdminApi) GetGroup() []string {
	var data []string

	Db.Model(AdminApi{}).Group("group_name").Pluck("group_name", &data)

	return data
}

// @title 删除
func (a *AdminApi) Delete(ids string) error {
	res := Db.Delete(AdminApi{}, "id in (?)", strings.Split(ids, ","))

	if res.Error != nil {
		logs.Error(res.Error.Error())
		return res.Error
	}

	return nil
}

// @title 获取单条数据
func (a *AdminApi) GetOne(id string) AdminApi {
	var data AdminApi

	Db.Model(AdminApi{}).Where("id = ?", id).First(&data)

	return data
}

// @title 添加
func (a *AdminApi) Store() error {
	if a.Path == "" {
		return errors.New("path不能为空")
	}

	var count int64

	Db.Model(AdminApi{}).Where("path = ?", a.Path).Where("method = ?", a.Method).Count(&count)

	if count > 0 {
		return errors.New("path已存在")
	}

	a.Id = 0

	return Db.Model(AdminApi{}).Create(&a).Error
}

// @title 更新
func (a *AdminApi) Update() error {
	if a.Path == "" {
		return errors.New("path不能为空")
	}

	var count int64

	Db.Model(AdminApi{}).Where("path = ?", a.Path).Where("method = ?", a.Method).Where("id != ?", a.Id).Count(&count)

	if count > 0 {
		return errors.New("path已存在")
	}

	return Db.Model(AdminApi{}).Where("id = ?", a.Id).Save(&a).Error
}
